package com.jxd.petMgr.servlet;

import com.jxd.petMgr.model.Pet;
import com.jxd.petMgr.model.PetOwner;
import com.jxd.petMgr.service.IPetOwnerService;
import com.jxd.petMgr.service.IPetService;
import com.jxd.petMgr.service.impl.PetOwnerServiceImpl;
import com.jxd.petMgr.service.impl.PetServiceImpl;
import com.jxd.petMgr.util.PageUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@WebServlet("/ownerPetListServlet")
public class OwnerPetListServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        IPetService petService = new PetServiceImpl();
        IPetOwnerService petOwnerService = new PetOwnerServiceImpl();
        PageUtil pageUtil = new PageUtil();
        //如果开启分页会向servlet传两个参数page   limit
        int page = Integer.parseInt(request.getParameter("page"));
        int limit = Integer.parseInt(request.getParameter("limit"));
        //判断主人的余额是否充足
        HttpSession session = request.getSession();
        //通过session取到的对象只有id是准确的，其他属性不一定准确
        PetOwner master = (PetOwner) session.getAttribute("petOwner");
        int petOwnerId = master.getId();
//        PetOwner petOwner = petOwnerService.getOwnerByID(petOwnerId);
        int count = petService.getPetByPetOwnerIdCount(petOwnerId);
        //设置分页工具
        pageUtil.setCount(count);
        pageUtil.setCurrentPage(page);
        pageUtil.setLimit(limit);
        List<Pet> petList = petService.getPetByPetOwnerId(pageUtil,petOwnerId);
//        List<Map<String,Object>> petList = petService.getAllPetHaveShopName(pageUtil,mapInfo);
        JSONArray jsonArray = JSONArray.fromObject(petList);
        JSONObject jsonObject = new JSONObject();
        //封装数据
        jsonObject.put("code",0);
        jsonObject.put("msg","");
        jsonObject.put("count",count);
        jsonObject.put("data",jsonArray);
        //使用输出流的方式向页面输出信息
        //不能使用请求转发或重定向，会无限循环
        PrintWriter pw = response.getWriter();
        //直接将对象以字符串形式输出页面
        pw.print(jsonObject.toString());
        pw.flush();
        pw.close();
    }
}
